import { useEffect, useState, useRef } from "react";
import { PageContainer, FooterToolbar } from "@ant-design/pro-layout";
import ProCard from "@ant-design/pro-card";
import ProForm, {
  ModalForm,
  ProFormDigit,
  ProFormSelect,
} from "@ant-design/pro-form";
import { useLocation, history } from "umi";
import {
  orderDetail,
  cancelOrder_waitPay,
  cancelOrder_isPay,
  deliver_goods,
  getPullData
} from "@/api/order";
import { Table, Button, Descriptions, message, Popconfirm, Image } from "antd";
import { filterOrderStatusOptions, nameListOptions } from "@/const";
import { LeftOutlined } from "@ant-design/icons";
import ScanRasCode from "./components/ScanRasCode";
import sendMsg2Print from "@/ws";

export default () => {
  const location = useLocation();
  const { orderId, orderCategory } = location.query;
  const [info, setInfo] = useState({});

  const getInfo = async () => {
    const res = await orderDetail({ orderId, orderCategory });
    if (res.code == 200) {
      setInfo(res.data);
    }
  };

  useEffect(() => {
    getInfo();
  }, []);

  const columns = [
    {
      title: "商品信息",
      dataIndex: "shop",
      search: false,
      render: (_, record) => {
        return (
          <>
            <div key={record.id} style={{ display: "flex", marginBottom: 10 }}>
              <Image width={80} height={80} src={record.picture} />
              <div style={{ marginLeft: 8 }}>
                <div>{record.title}</div>
              </div>
            </div>
          </>
        );
      },
    },
    {
      title: "单价",
      dataIndex: "unitPrice",
      render: (_, record) => {
        return `￥${record.unitPrice}`;
      },
    },
    {
      title: "数量",
      dataIndex: "quantity",
    },
    {
      title: "小计",
      dataIndex: "total",
      render: (_, record) => {
        return `￥${record.quantity * record.unitPrice}`;
      },
    },
  ];

  const renderSendModal = (record) => {
    return (
      <ModalForm
        title="发货"
        trigger={
          <Button type="primary" style={{ marginLeft: 20 }}>
            发货
          </Button>
        }
        onFinish={async (values) => {
          const res = await deliver_goods({
            orderId: record.orderId,
            addressId: record.addressId,
            orderCategory: record.orderType,
            ...values,
          });
          if (res.data) {
            message.success("发货成功");
            getInfo();
          }
        }}
      >
        <ProFormSelect
          name="name"
          label="商品描述"
          allowClear
          fieldProps={{
            options: nameListOptions,
          }}
          rules={[{ required: true, message: "请选择商品描述" }]}
        />
        <ProFormDigit
          label="包裹数量"
          name="quantity"
          placeholder="请输入包裹数量"
          min={1}
          rules={[{ required: true, message: "请输入包裹数量" }]}
        />

        <ProForm.Item
          label="芯片码"
          name="rasCodeList"
          rules={[{ required: true, message: "请扫码芯片码" }]}
        >
          <ScanRasCode />
        </ProForm.Item>
      </ModalForm>
    );
  };

  return (
    <PageContainer
      header={{
        title: (
          <div className="pointer" onClick={() => history.goBack()}>
            <LeftOutlined style={{ marginRight: 10 }} />
            订单详情
          </div>
        ),
        breadcrumb: {},
      }}
    >
      <ProCard style={{ marginTop: 20 }} title="订单信息" bordered>
        <Descriptions
          column={3}
          extra={
            <>
              {(info.orderStatus == 1 || info.orderStatus == 2) && (
                <Popconfirm
                  key="remove"
                  title="确定取消订单?"
                  onConfirm={async () => {
                    const func = {
                      1: cancelOrder_waitPay, // 未付款的取消订单
                      2: cancelOrder_isPay, // 已付款（未发货）的取消订单
                    };
                    const carData = {};
                    info?.articlesVOS.forEach((item) => {
                      carData[item.articlesId] = item.quantity;
                    });
                    const res = await func[info.orderStatus]({
                      carData,
                      orderId: info.orderId,
                      orderNum: info.orderNum,
                      orderType: info.orderType,
                      quantity: info.articlesVOS?.[0]?.quantity, // 直接购买需要传
                      refundType: 0, // 退款方式：0:全部退款 1:部分退款 支持商户自定义退款金额,但不得大于订单总金额
                    });
                    if (res.data) {
                      message.success("取消成功");
                      if (info.orderStatus == 1) {
                        history.goBack();
                      } else {
                        getInfo();
                      }
                    }
                  }}
                >
                  <Button type="danger">取消订单</Button>
                </Popconfirm>
              )}

              {info.orderStatus == 2 && renderSendModal(info)}

              {info.orderStatus == 8 && (
                <>
                  <Popconfirm
                    key="remove"
                    title="确定打印运单?"
                    onConfirm={async () => {
                      const res = await getPullData({
                        orderId: info.orderId,
                      });
                      if (res.data) {
                        // webSocket 调起打印
                        sendMsg2Print(res.data);
                        message.success("打印成功");
                        actionRef.current?.reload();
                      }
                    }}
                  >
                    <Button type="primary" style={{ marginRight: 8 }}>
                      打印运单
                    </Button>
                  </Popconfirm>
                </>
              )}
            </>
          }
        >
          <Descriptions.Item label="订单状态">
            {filterOrderStatusOptions(info?.orderStatus)}
          </Descriptions.Item>
          <Descriptions.Item label="订单号">{info.orderNum}</Descriptions.Item>

          <Descriptions.Item label="商品总额">
            ￥{info.amount - info.freight}
          </Descriptions.Item>
          <Descriptions.Item label="运费">￥{info.freight}</Descriptions.Item>

          <Descriptions.Item label="订单总额">
            ￥{info.amount}
          </Descriptions.Item>

          <Descriptions.Item label="下单时间">
            {info.createTime}
          </Descriptions.Item>
          {/* <!-- 待发货 卖家已经发货（待收货）订单已完成 已取消--> */}
          {(info.orderStatus == 2 ||
            info.orderStatus == 3 ||
            info.orderStatus == 4 ||
            info.orderStatus == 5) && (
            <Descriptions.Item label="支付时间">
              {info.payTime}
            </Descriptions.Item>
          )}

          {/* <!-- 订单已完成才展示 --> */}
          {info.orderStatus == 4 && (
            <>
              <Descriptions.Item label="收货时间">
                {info.receiveGoodsTime}
              </Descriptions.Item>
              <Descriptions.Item label="支付方式">微信支付</Descriptions.Item>
            </>
          )}

          {/* <!-- 订单已取消才展示 --> */}
          {info.orderStatus == 5 && (
            <>
              <Descriptions.Item label="取消时间">
                {info.cancelTime}
              </Descriptions.Item>
            </>
          )}

          <Descriptions.Item label="订单类型">
            {info.orderNormal == 1 ? "兑换订单" : "普通订单"}
          </Descriptions.Item>
        </Descriptions>
      </ProCard>

      <ProCard style={{ marginTop: 20 }} title="收货人信息" bordered>
        <Descriptions column={2}>
          <Descriptions.Item label="收货人">{info.receiver}</Descriptions.Item>
          <Descriptions.Item label="手机号">{info.mobile}</Descriptions.Item>
          <Descriptions.Item label="收货地址">
            {info.province}
            {info.city}
            {info.area}
            {info.detail}
          </Descriptions.Item>
        </Descriptions>
      </ProCard>

      <ProCard style={{ marginTop: 20 }} title="商品信息" bordered>
        <Table
          columns={columns}
          pagination={false}
          dataSource={info?.articlesVOS}
        />
      </ProCard>
    </PageContainer>
  );
};
